#!/usr/bin/env python
# -*- coding: utf-8 -*-


""" a robot
"""


from gevent import socket
import struct
import uuid

import pq_quota_pb2


# -----------------------------------------------------------------------------
class PreQuotation(object):
    def __init__(self, app, addr):
        self.addr = addr
        self.pre_quo_svr = self.connect_server(addr)
        self.subscibe()

    def connect_server(self, addr):
        svr = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        svr.connect(addr)
        return svr

    def subscibe(self):
        print('subscibe')
        submsg = pq_quota_pb2.PreQuoSubMsg()
        submsg.sub_flag = 1
        submsg.sub_type.append(0x5400)
        fmt = ">iHH16s"

        seq16 = uuid.uuid4()
        headbuffer = struct.pack(fmt, submsg.ByteSize(), 0x8001,
                                 0x5900,
                                 seq16.get_bytes())
        sentdata = headbuffer + submsg.SerializeToString()
        self.pre_quo_svr.sendall(sentdata)

    def recv_subscribe(self):
        while 1:
            header = ''
            while len(header) < 24:
                try:
                    hpdata = self.pre_quo_svr.recv(24 - len(header))
                except:
                    print('except ')
                    break
                if not hpdata:
                    print 'no header'
                    break
                header += hpdata

            if len(header) == 24:
                fmt = '>iHH16s'
                blen, sysid, cmd, s = struct.unpack(fmt, header)
            else:
                break

            if blen < 0:
                print 'close connect error length', blen
                break

            # 获取包体 收全包体
            body = ''
            while len(body) < blen:
                bpdata = self.pre_quo_svr.recv(blen - len(body))
                if not bpdata:
                    print 'no body'
                    break
                body += bpdata

            if len(body) != blen:
                break

            if 0x5400 == cmd:
                etfbase = pq_quota_pb2.EtfBasketInfo()
                etfbase.ParseFromString(body)
                self.etf_base_info_handle(etfbase)

    def etf_base_info_handle(self, pi):
        print pi


# -----------------------------------------------------------------------------
def main():
    pre_quo = PreQuotation(None, ('192.168.1.176', 9114))
    pre_quo.recv_subscribe()


if __name__ == '__main__':
    main()
